var udp = require('dgram');
let createUdp = require("./createUdp").createUdp;
let configpath = require("./getConfig").ev.path;
let config1 = require(configpath);
let sendBroad = require("./borderServer.js").sendBroad;// 依赖外部
global.createUdp = createUdp;
let delayclose = config1.delayclose;
console.log("代理端启动中：");
Rtur = {};
module.exports.Rtur = Rtur;//引用
function udpProxy(udplistenport, udplistenIp, udpturnport, udpturnIp) {
    let u = createUdp(udplistenport, udplistenIp, function () { u.setBroadcast(true) });
    //let boradServer = createUdp(0, "127.0.0.1");
    console.log(`udp转发:${udplistenIp}:${udplistenport}<==> ${udpturnIp}:${udpturnport}`);
    // 回发功能 ///转发到服务器功能
    u.on('message', (msg, rinfo) => {
        let addrstr = rinfo.address + ":" + rinfo.port;
        if (!Rtur[addrstr]) { // 创建临时实例
            let tem = createUdp(0, "0.0.0.0");
            tem.on('message', (msg, rinfo) => {
                u.send(msg, tem.fromport, tem.fromaddress); //临时实例收到数据转发给客户端
            });
            sendBroad(`from:${addrstr},go:${config1.go}`);// 广播新增用户
            Rtur[addrstr] = tem;
            // 绑定事件
        }
        let tem = Rtur[addrstr];
        tem.fromaddress = rinfo.address;
        tem.fromport = rinfo.port;
        //  tem.time=Date.parse(new Date());
        tem.send(msg, udpturnport, udpturnIp);//临时实例收到数据发给服务器

        tem.timeId && clearTimeout(tem.timeId);
        tem.unref();
        tem.timeId = setTimeout(function () {
            console.log("当前链接已经结束");
            tem.ref();
            delete Rtur[addrstr];
        }.bind(this), delayclose);
    });//  服务端口
       u.on('connect', (msg, rinfo) => {
            //  console.log(`receive message from ${rinfo.address}:${rinfo.port}`);
            // server.send(msg,rinfo.port)
        });//  服务端口
}
process.on('uncaughtException', function (e) {
    console.log(e);
});
module.exports.udpProxy = udpProxy;